from collections import OrderedDict

from django.shortcuts import render

# Create your views here.
from django.views import View

from contents.models import ContentCategory
from goods.models import GoodsChannel
from rest_framework.generics import ListAPIView

from goods.models import SKU

from apps.goods.serializers import SKUSerializer


class IndexView(View):
    def get(self, request):
        # 使用有序字典保存类别的顺序
        # categories = {
        #     1: { # 组1
        #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
        #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
        #     },
        #     2: { # 组2
        #
        #     }
        # }
        # 初始化存储容器
        categories = OrderedDict()
        # 获取一级分类
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')

        # 对一级分类进行遍历
        for channel in channels:
            # 获取group_id
            group_id = channel.group_id
            # 判断group_id 是否在存储容器,如果不在就初始化
            if group_id not in categories:
                categories[group_id] = {
                    'channels': [],
                    'sub_cats': []
                }

            one = channel.category
            # 为channels填充数据
            categories[group_id]['channels'].append({
                'id': one.id,
                'name': one.name,
                'url': channel.url
            })
            # 为sub_cats填充数据
            for two in one.goodscategory_set.all():
                # 初始化 容器
                two.sub_cats = []
                # 遍历获取
                for three in two.goodscategory_set.all():
                    two.sub_cats.append(three)

                # 组织数据
                categories[group_id]['sub_cats'].append(two)

        # 广告和首页数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        # content_categories = [{'name':xx , 'key': 'index_new'}, {}, {}]

        # {
        #    'index_new': [] ,
        #    'index_lbt': []
        # }
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 加载模版，组织上下文，渲染数据
        context = {
            'categories': categories,
            'contents': contents
        }
        return render(request, 'index.html', context)


# 第一种思路: 可以通过APIView进行 递进式的尝试 实现功能之后再 转换为ListAPIView
# 第二个思路: 直接继承自ListAPIView ,如果ListAPIView不能满足条件(重写指定方法或者回退)
# GenericAPIVew
class HotSKUView(ListAPIView):
    """
    GET  /goods/categories/(?P<category_id>\d+)/hotskus/
    根据我们的分类进行热销产品的查询，查询之后，进行序列化操作
    """
    serializer_class = SKUSerializer

    # 查询结果集
    # queryset = SKU.objects.all()

    # self指的就是ListAPIView，调用self.kwargs调用它的get方法中的**kwargs
    # 关键尖子参数category_id会通过**kwargs传递过去
    def get_queryset(self):
        category_id = self.kwargs['category_id']
        # is_launched是判断商品是否上架，可以不写，默认为1                      根据销量，降序排列  取出两条数据(查询结果集课件中)
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        return skus
